/**
 * Copyright (C) 2011 Moss Computing <support@mosscomputing.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.oslef.csv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;

public final class CSVReader {

	private char delimiter = ',';
	
	private BufferedReader in;
	private String currentLine;
	
	public CSVReader(File file) throws IOException {
		in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
	}
	
	public CSVReader(URL url) throws IOException {
		in = new BufferedReader(new InputStreamReader(url.openStream()));
	}
	
	public CSVReader(InputStream in) {
		this.in = new BufferedReader(new InputStreamReader(in));
	}
	
	public CSVReader(Reader in) {
		this.in = new BufferedReader(in);
	}
	
	public boolean hasNext() throws IOException {
		return in.ready();
	}
	
	public String[] next() throws IOException {
		currentLine = null;
		String[] values;
		do{
			if (!hasNext()){throw new IOException("End of file");}
			currentLine = currentLine==null?in.readLine():currentLine + '\n' + in.readLine();
			values = RowParser.parse(currentLine, delimiter);
		}while(values==null);

		columns = values;

		return columns;
	}
	
	public String getCurrentLine() {
		return currentLine;
	}
	
	private String[] columns;
	
	public String[] getColumns() {
		return columns;
	}
	
	public String getStringValue(int column) {
		String s = getColumns()[column];
		return s;
	}
	
	public Boolean getBooleanValue(int column) {
		String value = getStringValue(column);
		if (value == null || value.equals("N") || value.equalsIgnoreCase("false")) {
			return Boolean.FALSE;
		}
		else {
			return Boolean.TRUE;
		}
	}
	
	public BigDecimal getBigDecimalValue(int column) {
		String value = getStringValue(column);
		if (value != null) {
			return new BigDecimal(value);
		}
		else {
			return null;
		}
	}
	
	public Long getLongValue(int column) {
		String value = getStringValue(column);
		
		if (value != null) {
			return new Long(value);
		}
		else {
			return null;
		}
	}
	
	public void close() throws IOException {
		if (in != null) in.close();
	}

	public char getDelimiter() {
		return delimiter;
	}

	public void setDelimiter(char delimiter) {
		this.delimiter = delimiter;
	}
}
